package com.hcbd.tdwt.ui.fuda.common.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.util.StringUtil;
import com.hcbd.tdwt.view.MultiLineRadioGroup;
import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;
import com.hcbd.tdwt.ui.xingyu.vo.Position;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.Objects;

import static com.hcbd.tdwt.base.GlobalParams.sendBeidouMsgSignalEnable;


@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_app_sos_fuda)
public class AppSosFragment extends BaseFragment implements MainApp.LocationInfoInterface{
    @ViewById
    MultiLineRadioGroup urgentRG, healthStatusRG;
    @ViewById(R.id.choose_contact_img)
    ImageView chooseContactImg;
    @ViewById
    EditText phoneNum;
    @ViewById(R.id.cut_img)
    ImageView cutImg;
    @ViewById(R.id.add_img)
    ImageView addImg;
    @ViewById(R.id.people_num_tv)
    TextView peopleNumTv;
    @ViewById
    Button sendBtn;
    @ViewById(R.id.position_info)
    TextView positionInfo;
    @ViewById
    RadioButton emergency_1, healthStatus_1;

    public String emergencyStatus = "00";
    public String healthStatus = "00";
    //人数
    private int num = 1;
    SharedPreferencesUtil sp;
    Drawable lineColorDrawable;
    Drawable lightBlueDrawable;
    @AfterViews
    protected void init() {
        urgentRG.setOnCheckedChangeListener((radioGroup, i) -> selectEmergencyRadioBtn());
        healthStatusRG.setOnCheckedChangeListener((radioGroup, i) -> selectHealthStatusRadioBtn());
        lineColorDrawable = getResources().getDrawable(R.drawable.button_gray_bg);
        lightBlueDrawable = getResources().getDrawable(R.drawable.btn_light_blue_cilck_bg);
        sp = new SharedPreferencesUtil(getContext());
        String lastNumber = sp.getAttribute(Constant.LAST_SOS_NUMBER);
        if (!TextUtils.isEmpty(lastNumber)) {
            phoneNum.setText(lastNumber);
        }
        isRefreshing = true;
        initGPS();
        emergency_1.setChecked(true);
        healthStatus_1.setChecked(true);
        refreshStatus();
        positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
        initMsgRegister();
    }

    void selectEmergencyRadioBtn() {
        RadioButton rb = Objects.requireNonNull(this.getActivity()).findViewById(urgentRG.getCheckedRadioButtonId());
        emergencyStatus = rb.getTag().toString();
    }


    void selectHealthStatusRadioBtn() {
        RadioButton rb = Objects.requireNonNull(this.getActivity()).findViewById(healthStatusRG.getCheckedRadioButtonId());
        String tag = rb.getTag().toString();
        healthStatus = tag;
    }

    @Click(R.id.choose_contact_img)
    void chooseContactImg() {
        openContacts();
    }

    @Click
    void cutImg() {
        //减号
        if (num > 1) {
            num--;
            peopleNumTv.setText(String.valueOf(num));
        }
    }

    @Click
    void addImg() {
        //加号
        if (num < 255) {
            num++;
            peopleNumTv.setText(String.valueOf(num));
        }
    }

    @Click
    void sendBtn() {
        String phone = getTextStr(phoneNum);
        if (TextUtils.isEmpty(phone)) {
            toast("联系人号码不能为空");
            return;
        }
        if (phone.length() != 11) {
            toast("联系人号码格式不对");
            return;
        }
        if (!StringUtil.isMobilePhone(phone)) {
            toast("联系人号码格式不对");
            return;
        }
        Position position = new Position();
        position.setLongitude(GlobalParams.gpsLongitude);
        position.setLatitude(GlobalParams.gpsLatitude);
        position.setAltitude(GlobalParams.gpsAltitude);
        position.setTime(Long.parseLong(DateUtils.getTimeStamp()));
        if (BeidouBoxParams.isBoxConnectNormal) {
            //没有公网的情况使用北斗网发送
            sendByBeidou(phone, position, emergencyStatus, healthStatus, num);
        } else {
            toast("请连接终端！");
        }

    }

    /**
     * 通过北斗网发送
     */
    private void sendByBeidou(String phone, Position position, String situation, String healthStatus, int num) {
        int beidouSignal = BeidouBoxParams.getBdSignal();
        if (beidouSignal < sendBeidouMsgSignalEnable) {
            toast("信号不好，请移动终端位置");
            return;
        }
        String content = ConvertToBdMsgTool.castUserMessageTo0x13(phone, position, situation, healthStatus, num);

        BdToolFactory.getBdSendBase().sendMsg(GlobalParams.rdCentreNumber,2,2,content);

        //最后一次发送的号码
        sp.addAttribute(Constant.LAST_SOS_NUMBER, phone);
        // 发送状态倒计时线程
        MainApp.getInstance().startNewSentWaitSecTimer();
        toast("发送成功");
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSnrInfo bdSnrInfo){
        if(BeidouBoxParams.sentWaitSec > 0){
            return;
        }
        refreshStatus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(String bleContent){
        if("onConnectError".equals(bleContent)){
            noConBtn();
        }
    }


    @OnActivityResult(Constant.GET_MAIL_LIST_CONTACT_RESULT)
    public void getContactResult(int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                phoneNum.setText(getPhoneNum(data));
            }
        }
    }

    @OnActivityResult(Constant.TO_OPEN_GPS_REQUEST_CODE)
    public void toOpenGpsRequestCode(int resultCode) {
        if (resultCode == Activity.RESULT_OK) {
            MainApp.getInstance().initMap();
        }
    }


    /**
     * 刷新终端信息
     */
    private void refreshStatus() {
        if (!isRefreshing) {
            return;
        }
        if(BeidouBoxParams.isBoxConnectNormal){
            int bdSignal = BeidouBoxParams.getBdSignal();
            if (BeidouBoxParams.sentWaitSec > 0) {
                sendBtn.setClickable(false);
                sendBtn.setText(MessageFormat.format("{0}S", BeidouBoxParams.sentWaitSec));
                sendBtn.setBackground(lineColorDrawable);
            } else if (bdSignal < sendBeidouMsgSignalEnable) {
                sendBtn.setClickable(false);
                sendBtn.setText("没信号");
                sendBtn.setBackground(lineColorDrawable);
            } else {
                sendBtn.setClickable(true);
                sendBtn.setText("发送");
                sendBtn.setBackground(lightBlueDrawable);
            }
        }else{
            noConBtn();
        }

    }


    private void initGPS() {
        LocationManager locationManager = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            toast("请开启手机定位!");
        } else {
            MainApp.getInstance().initMap();
        }
    }

    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler adapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_STATUS_CODE) {
                refreshStatus();
            } else if (msg.what == REFRESH_LOCATION_INFO_CODE) {
                if ("".equals(BeidouBoxParams.gpsLongitude) || "".equals(BeidouBoxParams.gpsLatitude)) {
                    positionInfo.setText("未知");
                } else {
                    positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
                }
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isRefreshing = false;
    }

    private final int REFRESH_STATUS_CODE = 5;
    private final int REFRESH_LOCATION_INFO_CODE = 6;
    private boolean isRefreshing = false;

    @Override
    public void LocationInfo() {
        Message msg = new Message();
        msg.what = REFRESH_LOCATION_INFO_CODE;
        adapterHandler.sendMessage(msg);
    }

    public void noConBtn() {
        sendBtn.setClickable(false);
        sendBtn.setText("未连接！");
        sendBtn.setBackground(lineColorDrawable);
    }

    @Override
    public void onSwitch() {
        if (positionInfo != null) {
            positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
        }
        MainApp.getInstance().setLocationInfoInterface(this);
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            hideInputKeyBord();
        }
    }
    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true, priority = 2)
    public void eventBus(int delaySeconds){
        Message msg = new Message();
        msg.what = REFRESH_STATUS_CODE;
        adapterHandler.sendMessage(msg);
    }
}